package net.guerlab.sdk.dingtalk.autoconfigure.storage;

import lombok.extern.slf4j.Slf4j;
import net.guerlab.sdk.dingtalk.autoconfigure.DingTalkProperties;
import net.guerlab.sdk.dingtalk.storage.DingTalkConfigRedisTemplateStorage;
import net.guerlab.sdk.dingtalk.storage.DingTalkConfigStorage;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.*;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.NonNull;

/**
 * 钉钉配置储存接口自动配置
 *
 * @author guer
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Slf4j
@Configuration
@Conditional(DingTalkRedisTemplateStorageAutoConfiguration.WrapperCondition.class)
public class DingTalkRedisTemplateStorageAutoConfiguration {

    @Bean
    @RefreshScope
    public DingTalkConfigStorage dingTalkConfigRedisTemplateStorage(DingTalkProperties properties,
            RedisTemplate<String, String> redisTemplate) {
        log.debug("init redisTemplate storage");
        DingTalkConfigStorage storage = new DingTalkConfigRedisTemplateStorage(redisTemplate);
        storage.setCorpId(properties.getCorpId());
        storage.setAppKey(properties.getAppKey());
        storage.setAppSecret(properties.getAppSecret());
        return storage;
    }

    @SuppressWarnings("WeakerAccess")
    static class WrapperCondition implements Condition {

        @Override
        public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) {
            try {
                return WrapperCondition.class.getClassLoader()
                        .loadClass("org.springframework.data.redis.core.RedisTemplate") != null;
            } catch (Exception e) {
                return false;
            }
        }
    }
}
